<?php

namespace app\common\model;

use think\Db;
use think\Model;

class Category extends Model
{
    /**
     * 获取分类树
     * @param int $pid
     * @return mixed
     */
   public function getCateTreeByPid($pid = 0) {
       $tree = get_cates($pid);
       return $tree;
   }

    /**
     * 获取分类数  zTree插件
     * @param int $id  @排除当前分类以及其子分类
     * @return mixed
     */
    public function getCateZTree($id = 0) {
        $where = [
            'status' => 1,
            'delete' => 0
        ];
        if ($id > 0) {
            //获取产品列表分类树
            $cate = $this->get(['id' => $id, 'status' => 1, 'delete' => 0]);
            if ($cate['level'] == 3) {
                $where['id'] = ['neq', $id];
            } else if ($cate['level'] == 2) {
                $ids = $this->where('pid', $id)->column('id');
                $where['id'] = ['not in', $id . ',' . implode(',', $ids)];
            } else {
                $ids_2 = $this->where('pid', $id)->where('delete', 0)->where('status', 1)->column('id');

                $ids_3 = [];
                if ($ids_2) {
                    $ids_3 = $this->where('pid', 'in', $ids_2)->column('id');
                }
                $where['id'] = ['not in', $id . ',' . implode(',', $ids_2) . ',' . implode(',', $ids_3)];
            }
        } else {
            $ids_1 = $this->where('pid', 0)->where('delete', 0)->where('status', 1)->column('id');
            $ids_2 = $ids_3 = [];
            if ($ids_1) {
                $ids_2 = $this->where('pid', 'in', $ids_1)->where('delete', 0)->where('status', 1)->column('id');
                if ($ids_2) {
                    $ids_3 = $this->where('pid', 'in', $ids_2)->column('id');
                }
            }
            $where['id'] = ['in', implode(',', $ids_1) . ',' . implode(',', $ids_2) . ',' . implode(',', $ids_3)];
        }

        $data = $this->all($where);
        //树部分
        $ztree = "[{id:0, pId:'', name:'/', open:true, nocheck: true},";
        foreach ($data as $v) {
            $ztree .= "{id:$v[id], pId:$v[pid], name:'$v[name]', nocheck: true},";
        }
        $ztree .= "]";
        return $ztree;
    }

    /**
     * 根据上级分类获取分类等级
     * @param $pid
     * @return mixed
     */
    public function getCategoryLevel($pid) {
        if ($pid == 0) {
            $level = 1;
        } else {
            $p_cate = $this->get(['id', $pid]);
            $level = $p_cate['level'] + 1;
        }
        return $level;
    }

    public function getCategory($where) {
        $where['status'] = 1;
        $where['delete'] = 0;
        return $this->get($where);
    }
}
